//
//  ScanQRViewController.m
//  Boomerang
//
//  Created by TH-MAC02 on 11/7/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "ScanQRViewController.h"

#import "PostClass.h"

#import "ParserClass.h"

#import "UserDetails.h"

#import "IIViewDeckController.h"

#import "UIManager.h"

@interface ScanQRViewController ()

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic) BOOL isReading;

-(BOOL)startReading;
-(void)stopReading;
-(void)loadBeepSound;

@end

@implementation ScanQRViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _captureSession = nil;
    
    // Set the initial value of the flag to NO.
    _isReading = NO;
    
    // Begin loading the sound effect so to have it ready for playback when it's needed.
    [self loadBeepSound];
    
    [self startReading];
}

-(void)viewWillAppear:(BOOL)animated{
    _captureSession = nil;
    
    // Set the initial value of the flag to NO.
    _isReading = NO;
    
    // Begin loading the sound effect so to have it ready for playback when it's needed.
    [self loadBeepSound];
    
    [self startReading];
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction method implementation

- (IBAction)startStopReading:(id)sender {
    if (!_isReading) {
        // This is the case where the app should read a QR code when the start button is tapped.
        if ([self startReading]) {
            // If the startReading methods returns YES and the capture session is successfully
            // running, then change the start button title and the status message.
            //     [_bbitemStart setTitle:@"Stop"];
            [_lblStatus setText:@"Scanning for QR Code..."];
        }
    }
    else{
        // In this case the app is currently reading a QR code and it should stop doing so.
        [self stopReading];
        // The bar button item's title should change again.
        //  [_bbitemStart setTitle:@"Start!"];
    }
    
    // Set to the flag the exact opposite value of the one that currently has.
    _isReading = !_isReading;
}



#pragma mark - Private method implementation

- (BOOL)startReading {
    NSError *error;
    
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    AVCaptureDevice *captureDevice = [self frontCamera];
    
    //[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    
    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!input) {
        // If any error occurs, simply log the description of it and don't continue any more.
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    // Initialize the captureSession object.
    _captureSession = [[AVCaptureSession alloc] init];
    // Set the input device on the capture session.
    [_captureSession addInput:input];
    
    
    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];
    
    // Create a new serial dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    
    
    // Start video capture.
    [_captureSession startRunning];
    
    return YES;
}
- (AVCaptureDevice *)frontCamera {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == AVCaptureDevicePositionBack) {
            return device;
        }
    }
    return nil;
}

-(void)stopReading{
    // Stop video capture and make the capture session object nil.
    [_captureSession stopRunning];
    _captureSession = nil;
    
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] getQRCodeLoad:_lblStatus.text andUserID:[userDetails idUser]];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    // Remove the video preview layer from the viewPreview view's layer.
    // [_videoPreviewLayer removeFromSuperlayer];
    
//    if ([useStr isEqualToString:@"Status"]) {
//        
//        NSString *strFilter = [((AppDelegate*)[[UIApplication sharedApplication] delegate]) filterWithID:_lblStatus.text];
//        
//        if ([strFilter isEqualToString:@"Data Found"]) {
//            
//            //            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) filterIn:_lblStatus.text andStatus:[[ParserClass sharedItems] status] andAction:[[ParserClass sharedItems] action] andCompany:_companyTxt.text];
//            //
//            //            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDataFromCoreData];
//            //
//            //            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Successful" message:@"Data Found" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
//            //
//            //            [alertView show];
//            
//            
//            //   dispatch_async(kBgQueue, ^{
//            
//            NSData *data = [[PostClass sharedItems] viewLogs:_lblStatus.text];
//            
//            [self performSelectorOnMainThread:@selector(fetchedData:)
//                                   withObject:data waitUntilDone:YES];
//            
//            // });
//            
//            
//            
//            
//            
//            
//        }else if ([strFilter isEqualToString:@"Not Found"]){
//            
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Scan a valid QR code" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
//            
//            [alertView show];
//            
//        }
//        
//        
//        
//    }else{
//        
//        if ([[[ParserClass sharedItems] action] isEqualToString:@"Meeting"]) {
//            
//            if ([self.companyTxt.text isEqualToString:@""]) {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Please complete the details." delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
//                
//                [alert show];
//            }else{
//                
//                [self submitData];
//            }
//        }else{
//            
//            [self submitData];
//        }
//        
//    }
}


-(void)loadBeepSound{
    // Get the path to the beep.mp3 file and convert it to a NSURL object.
    NSString *beepFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
    NSURL *beepURL = [NSURL URLWithString:beepFilePath];
    
    NSError *error;
    
    // Initialize the audio player object using the NSURL object previously set.
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:beepURL error:&error];
    if (error) {
        // If the audio player cannot be initialized then log a message.
        NSLog(@"Could not play beep file.");
        NSLog(@"%@", [error localizedDescription]);
    }
    else{
        // If the audio player was successfully initialized then load it in memory.
        [_audioPlayer prepareToPlay];
    }
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate method implementation

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    // Check if the metadataObjects array is not nil and it contains at least one object.
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        // Get the metadata object.
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            // If the found metadata is equal to the QR code metadata then update the status label's text,
            // stop reading and change the bar button item's title and the flag's value.
            // Everything is done on the main thread.
            [_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            [_bbitemStart performSelectorOnMainThread:@selector(setTitle:) withObject:@"Start!" waitUntilDone:NO];
            
            _isReading = NO;
            
            // If the audio player is not nil, then play the sound effect.
            if (_audioPlayer) {
                [_audioPlayer play];
                
                
                
                
                
            }
        }
    }
    
    
}

- (void)viewWillLayoutSubviews {
    _videoPreviewLayer.bounds = self.viewPreview.layer.bounds;
    if (_videoPreviewLayer.connection.supportsVideoOrientation) {
        _videoPreviewLayer.connection.videoOrientation = [self interfaceOrientationToVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
    }
}


- (AVCaptureVideoOrientation)interfaceOrientationToVideoOrientation:(UIInterfaceOrientation)orientation {
    switch (orientation) {
        case UIInterfaceOrientationPortrait:
            return AVCaptureVideoOrientationPortrait;
        case UIInterfaceOrientationPortraitUpsideDown:
            return AVCaptureVideoOrientationPortraitUpsideDown;
        case UIInterfaceOrientationLandscapeLeft:
            return AVCaptureVideoOrientationLandscapeLeft;
        case UIInterfaceOrientationLandscapeRight:
            return AVCaptureVideoOrientationLandscapeRight;
        default:
            break;
    }
    NSLog(@"Warning - Didn't recognise interface orientation (%d)",orientation);
    return AVCaptureVideoOrientationPortrait;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            NSLog(@"received Data = %@", _receivedData);
            
            NSString *strReturn = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
            
            NSLog(@"return = %@", strReturn);
            
            self.viewDeckController.centerController = [[UIManager sharedItems] homePageViewController];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userProfile" object:@"userProfile"];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Scan successfully" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
            
            [alertView show];
            
        }
        
        
        NSLog(@"Finish");
    }
    
}



@end
